package com.rong.juc_test.juc_base.readwrite;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 锁降级：
 * 1。 先获取写锁
 * 2。 再获取读锁
 * 3. 读锁可以获取到当前线程修改后的数据
 * 4. 最后再释放写锁
 *
 * 注意：读锁释放后，其他线程才能获取到写锁
 */
public class LockDownPower {
    private static int count;
    public static void main(String[] args) throws InterruptedException{
        ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
        ReentrantReadWriteLock.ReadLock readLock = lock.readLock();
        ReentrantReadWriteLock.WriteLock writeLock = lock.writeLock();

        CountDownLatch latch = new CountDownLatch(2);

        for (int i = 0; i < 2; i++){
            new Thread(() -> {
                writeLock.lock();
                try {
                    count++;
                    readLock.lock();
                    Thread.sleep(1000);
                    System.out.println(Thread.currentThread().getName() + "写入成功此时count:" + count);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    readLock.unlock();
                    writeLock.unlock();
                }
            },"线程 " + i).start();
            latch.countDown();
        }
        latch.await(); // 计数器清零后结束等待 主任务结束
    }
}
